<link rel="stylesheet" href="${request.contextPath}/assets/bower_components/jquery-ztree/zTreeStyle.css">
<link rel="stylesheet" href="${request.contextPath}/assets/bower_components/bootstrap-validator/dist/css/bootstrapValidator.css"/>
<script type="text/javascript" src="${request.contextPath}/assets/bower_components/bootstrap-validator/dist/js/bootstrapValidator.js"></script>
<script type="text/javascript" src="${request.contextPath}/assets/bower_components/bootstrap-validator/dist/js/language/zh_CN.js"></script>
<section class="content-header">
	<h1>&nbsp;</h1>
	<ol class="breadcrumb">
		<li><a><i class="fa fa-dashboard"></i>信息管理</a></li>
		<li class="active"><a>用户管理</a></li>
	</ol>
</section>
<!-- Main content -->
<section class="content" id="deviceContent">
	<div class="row">
		<div class="col-xs-12">
			<div class="box">
				<div class="box-body">
					<!-- 搜索条件 -->
					<table class="table">
						<tr height="45px" bgcolor="#F3F3F3">
						    <td align="left" style="width:250px;">
								<form action="#" method="get" class="">
							        <div class="input-group">
							          <input type="text" name="q" class="form-control" placeholder="Search...">
							              <span class="input-group-btn">
							                <button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i>
							                </button>
							              </span>
							        </div>
							      </form>
							</td>
							<td align="left">
								<button	class="btn btn-danger btn-small" data-toggle="modal" onclick="showadddialog();">添加</button>
							</td>
						</tr>
					</table>
					<!-- 结果列表 -->
					<table id="myTableData"
						class="table table-bordered table-condensed table-hover table-striped">
						<thead>
							<tr>
                                <th>ID</th>
								<th>序号</th>
								<th>登陆账号</th>
								<th>用户名称</th>
								<th>公司id</th>
                                <th>用户角色</th>
								<th>所属公司</th>
								<th>状态</th>
								<th>更新时间</th>
								<th>操作</th>
							</tr>
						</thead>
						<tbody>
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</div>
</section>

<div class="modal fade" id="modal-default">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="userdialogtitle">添加用户</h4>
      </div>
      <div class="modal-body">
        
        <form class="form-horizontal" id="defaultForm">
              <div class="box-body">
              
                <div class="form-group">
                  <label class="col-sm-2 control-label">所属公司</label>
                  <div class="col-sm-9">
                    	<input class='link-url form-control' id='pid' name="pid" type='text'
								onclick="showMenu();" placeholder='选择公司' readonly="true"/>
						<input type="hidden" id="parentid" name="parentid"/>
						<div id="menuContent" class="menuContent"
							style="display:none;position: absolute;z-index:999">
							<ul id="treeDemo" class="ztree"
								style="margin-top:0; width:130%;min-height: 215px;"></ul>
						</div>
                  </div>
                  <div class="col-sm-1">
                  	<span class="promptMsg" id="promptMsg_device_id1">*</span>
                  </div>
                </div>
                
                <div class="form-group">
                  <label for="account" class="col-sm-2 control-label">登录账号</label>
                  <div class="col-sm-9">
                  	<input type="hidden" class="form-control" id="userid">
                    <input type="text" class="form-control" id="account" name="account" placeholder="登录账号">
                  </div>
                  <div class="col-sm-1">
                  	<span class="promptMsg" id="promptMsg_device_id2">*</span>
                  </div>
                </div>
                <div class="form-group">
                  <label for="password" class="col-sm-2 control-label">用户名称</label>
                  <div class="col-sm-9">
                    <input type="text" class="form-control" id="name" name="name" placeholder="用户名称">
                  </div>
                  <div class="col-sm-1">
                  	<span class="promptMsg" id="promptMsg_device_id3">*</span>
                  </div>
                </div>
                <div class="form-group" id="pwd">
                  <label for="password" class="col-sm-2 control-label">登录密码</label>
                  <div class="col-sm-9">
                    <input type="password" class="form-control" id="password" name="password" placeholder="登录密码">
                  </div>
                  <div class="col-sm-1">
                  	<span class="promptMsg" id="promptMsg_device_id4">*</span>
                  </div>
                </div>
                <div class="form-group">
                  <label for="status" class="col-sm-2 control-label">是否禁用</label>
                  <div class="col-sm-10" style="line-height: 40px;">
                    <input type="checkbox" id="status">
                  </div>
                </div>
              </div>
              
              <div class="box-footer">
              	<div class="pull-right">
	              	<button type="button" id="saveuser" class="btn btn-info">确定</button>
	                &nbsp;&nbsp;&nbsp;&nbsp;<button type="button" class="btn btn-default pull-right" data-dismiss="modal">取消</button>
              	</div>
              </div>
            </form>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="newpassworddialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">修改密码</h4>
            </div>
            <div class="modal-body">

                <form class="form-horizontal">
                    <div class="box-body">
                        <div class="row">
                            <div class="col-sm-10"></div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2 "><label>新密码:</label></div>
                            <div class="col-sm-8">
                            	<input type="hidden" class="form-control" id="newuserid">
								<input type="password" class="form-control" id="newpassword" name="newpassword" placeholder="新密码">
                            </div>
                        </div>
                    </div>

                    <div class="box-footer">
                        <div class="pull-right">
                            <button type="button" class="btn btn-info" onclick="savenewpwd();">确定</button>
                            &nbsp;&nbsp;&nbsp;&nbsp;<button type="button" class="btn btn-default pull-right" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<#include './pop/popAuthority.html'/>

	<script type="text/javascript"
		src="${request.contextPath}/assets/bower_components/jquery-ztree/jquery.ztree.core-3.5.min.js"></script>
	<script type="text/javascript"
		src="${request.contextPath}/assets/bower_components/jquery-ztree/jquery.ztree.exedit-3.5.min.js"></script>
		
<script>
   
   $(function(){
	 $("#myTableData").dataTable({
		 lengthMenu: [10],//这里也可以设置分页，但是不能设置具体内容，只能是一维或二维数组的方式，所以推荐下面language里面的写法。
         paging: true,//分页
         ordering: true,//是否启用排序
         searching: false,//搜索
         language: {
       	  lengthMenu: '',//左上角的分页大小显示。
             paginate: {//分页的样式内容。
                 previous: "上一页",
                 next: "下一页",
                 first: "首页",
                 last: "末页"
             },
             zeroRecords: "没有内容",//table tbody内容为空时，tbody的内容。
             //下面三者构成了总体的左下角的内容。
             info: "总共_PAGES_ 页，显示第_START_ 到第 _END_条记录 ，记录总数： _TOTAL_条 ",//左下角的信息显示，大写的词为关键字。
             infoEmpty: "0条记录",//筛选为空时左下角的显示。
             infoFiltered: ""//筛选之后的左下角筛选提示，
         },
         pagingType: "full_numbers",//分页样式的类型
         "serverSide": true,
          ajax: function (data, callback, settings) {
              //封装请求参数
              var param = {};
              param.limit = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
              param.start = data.start;//开始的记录序号
              param.page = (data.start / data.length)+1;//当前页码
              param.orderby=data.orderBys;
              //ajax请求数据
              $.ajax({
                  type: "post",
                  url: "${request.contextPath}/user/getUserList",
                  cache: false,  //禁用缓存
                  data: param,  //传入组装的参数
                  dataType: "json",
                  success: function (result) {
                      //封装返回数据
                      var returnData = {};
                      returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                      returnData.recordsTotal = result.total;//返回数据全部记录
                      returnData.recordsFiltered = result.total;//后台不实现过滤功能，每次查询均视作全部结果
                      returnData.data = result.pageData;//返回的数据列表
                      //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                      //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                      callback(returnData);
                  }
              });
          },
          //列表表头字段
          columns: [
              { "data": "id" },
              { "data": null },
              { "data": "account" },
              { "data": "name" },
              { "data": "orgid" },
              { "data": "roleName" },
              { "data": "orgname" },
              { "data": "status" },
              { "data": "updatetime" },
              { "data": null}
          ],
         fnDrawCallback  : function(){
             this.api().column(1).nodes().each(function(cell, i) {
                 cell.innerHTML =  i + 1;
             });
         },
          "aoColumnDefs":[
              {
                  "targets":0,
                  "visible":false
              },
        	  {
        		  "targets":4,
        		  "visible":false
        	  },
              {//倒数第一列
                  "targets":-1,	
                  "bSortable": false,
                  render: function(data, type, row) {
                      var html ='<button class="btn btn-success btn-small" onclick="showeditdialog('+data.id+','+data.orgid+',\''+data.account+'\',\''+data.name+'\',\''+data.status+'\');">编辑</button>'
                      +'&nbsp;&nbsp;&nbsp;&nbsp;<button class="btn btn-success btn-small" onclick="editAuthority(\''+data.id+'\')">修改角色</button>'
                      +'&nbsp;&nbsp;&nbsp;&nbsp;<button class="btn btn-success btn-small" onclick="showpwddialog(\''+data.id+'\')">修改密码</button>'
                      /* +'&nbsp;&nbsp;&nbsp;&nbsp;<button class="btn btn-success btn-small" onclick="">分配车辆</button>' */
                      +'&nbsp;&nbsp;&nbsp;&nbsp;<button class="btn btn-danger btn-small" onclick="deluser(\''+data.id+'\');">删除</button>';
                      return html;
                  }
              },
           ]
      });
	
	   $.ajax({
			url : "${request.contextPath}/user/getTreeOrg",
			type : "post",
			success : function(data) {
				if (data.success && data.other) {
				   var setting = {
				   		view: {
				   			dblClickExpand: true
				   		},
				   		data: {
				   			simpleData: {
				   				enable: true
				   			}
				   		},
				   		callback: {
				   			onClick: onClick
				   		}
				   	};
				   var treeData = formatTreeImage(data.other);
			       $.fn.zTree.init($("#treeDemo"), setting, treeData);
			       $.fn.zTree.getZTreeObj("treeDemo").expandAll(true);//展开
				}
			}
		});
	   
	   
	   $('#defaultForm').bootstrapValidator({
	        message: '此值无效',
	        feedbackIcons: {
	            valid: 'glyphicon glyphicon-ok',
	            invalid: 'glyphicon glyphicon-remove',
	            validating: 'glyphicon glyphicon-refresh'
	        },
	        fields: {
	        	pid: {
	                validators: {
	                    notEmpty: {
	                        message: '所属公司不能为空'
	                    }
	                }
	            },
	            account: {
	                message: '登录名无效',
	                validators: {
	                    notEmpty: {
	                        message: '登录账号不能为空'
	                    },
	                    stringLength: {
	                        min: 6,
	                        max: 30,
	                        message: '登录名必须大于6，长度小于30个字符'
	                    },
	                    regexp: {
	                        regexp: /^[a-zA-Z0-9_\.]+$/,
	                        message: '用户名只能由字母、数字、点和下划线组成'
	                    }
	                }
	            },
	            name: {
	                validators: {
	                    notEmpty: {
	                        message: '用户名称不能为空'
	                    }
	                }
	            },
	            password: {
	                validators: {
	                    notEmpty: {
	                        message: '密码不能为空'
	                    }
	                }
	            }        
	        }
	    });
	   
	   $("#saveuser").on("click", function(){
		     //获取表单对象
		    var bootstrapValidator = $('#defaultForm').data('bootstrapValidator');
	        //手动触发验证
	        bootstrapValidator.validate();
	        if(bootstrapValidator.isValid()){
	            //表单提交的方法、比如ajax提交
	            saveuser();
	        }
		});
       $(".j-save-userrole").on("click", function(){
           var userid = $(".j-select-role select").attr('data-userid');
           var roleid = $(".j-select-role select").val();
			$.ajax({
				url:'${request.contextPath}/user/'+userid+'/role/'+roleid,
				type:'post',
				data:null,
				headers:{
				    Accept:'application/json'
				},
				contentType:'application/json',
				success:function(result){
                    $("#j-authority-pop").modal('hide')
				}
			})

       });

   }); 
   
   	function onClick(e, treeId, treeNode) {
   		var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
   		nodes = zTree.getSelectedNodes(),
   		v = "";
   		pv = "";
   		nodes.sort(function compare(a,b){return a.id-b.id;});
   		for (var i=0, l=nodes.length; i<l; i++) {
   			v += nodes[i].name + ",";
   			pv += nodes[i].id + ",";
   		}
   		if (v.length > 0 ) v = v.substring(0, v.length-1);
   		var cityObj = $("#pid");   		
   		cityObj.attr("value", v);
   		
   		if (pv.length > 0 ) pv = pv.substring(0, pv.length-1);
   		var cityObj2 = $("#parentid");
   		cityObj2.attr("value", pv);
   		
   		//移除校验
   		$('#defaultForm').data('bootstrapValidator')
        .updateStatus('pid', 'NOT_VALIDATED', null)
        .validateField('pid');
   		
   		hideMenu();
   	}

   	function showMenu() {
   		var cityObj = $("#pid");
   		var cityOffset = $("#pid").offset();
   		$("#menuContent").slideDown("fast");
   		$("body").bind("mousedown", onBodyDown);
   	}
   	function hideMenu() {
   		$("#menuContent").fadeOut("fast");
   		$("body").unbind("mousedown", onBodyDown);
   	}
   	function onBodyDown(event) {
   		if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
   			hideMenu();
   		}
   	}
   	
   function showadddialog()
   {
	   $("#userid").val("-1");
	   
	   $("#account").val("");
	   $("#account").removeAttr("readonly");
	   $("#name").val("");
	   $("#password").val("");
	   $("#pwd").show();
	   $("#status").prop("checked", false);
	   
	   $("#userdialogtitle").text("添加用户");
	   
	   $("#modal-default").modal('show');
   }
   
   function showpwddialog(id)
   {
	   $("#newpassword").val("");
	   $("#newuserid").val(id);
	   $("#newpassworddialog").modal('show');
   }
   
   function savenewpwd()
   {
	   var password = $("#newpassword").val();
	   var userid = $("#newuserid").val();
	   var data = {userid:userid,password:password}
	   $.ajax({
			url : "${request.contextPath}/user/resetUserPwd",
			type : "post",
			data : data,
			success : function(s) {
				if (s.success) {
					location.reload();
				} else {
					alert(s.msg);
				}
			}
		}); 
   }
   
   function showeditdialog(id,orgid,account,name,check)
   {
	   $("#userid").val(id);

	   //$("#parentid").val(orgid);
	   
	   var zTree = $.fn.zTree.getZTreeObj("treeDemo");
	   var snode = zTree.getNodeByParam("id",orgid, null);
	   
	   if (snode)
	   {
	    	$("#pid").attr("value",snode.name);
		    zTree.selectNode(snode);
		    $("#parentid").attr("value", orgid);
	   	}
		else
	   	{
	    	$("#pid").attr("value",'选择公司');
	    	$("#parentid").attr("value", 0);
	   	}
	   
	   
	   $("#account").val(account);
	   $("#name").val(name);
	   $("#account").attr("readonly","readonly");
	   $("#pwd").hide();
	   if (check == "禁用")
	   {
		   $("#status").prop("checked", true);
	   }
	   else
	   {
		   $("#status").prop("checked", false);   
	   }
	   $("#userdialogtitle").text("编辑用户");
	   $("#modal-default").modal('show');
   }
   
   function deluser(id)
   {
	   CvMsg.confirm("警告","数据删除后将无法还原！是否删除？",function(){
		   var data = {id:id}
		   $.ajax({
				url : "${request.contextPath}/user/delUser",
				type : "post",
				data : data,
				success : function(s) {
					if (s.success) {
						location.reload();
					} else {
						alert(s.msg);
					}
				}
			}); 
	   });
	   
   }
   
   function saveuser()
   {
	   var userid = $("#userid").val();
	   userid = parseInt(userid);
	   //公司ID
	   var orgid = $("#parentid").val();
	   orgid = parseInt(orgid);
	   var account = $("#account").val();
	   var name = $("#name").val();
	   var password = $("#password").val();
	   var status = 0;
	   var isselect = $("#status").is(':checked');
	   if (isselect)
	   {
		   status = 1;
	   }
	   else
	   {
		   status = 0;
	   }
	   if (userid == -1)
	   {
		   var data = {
			   orgid:orgid,
			   account:account,
			   name:name,
			   password:password,
			   status:status
		   }
		   $.ajax({
				url : "${request.contextPath}/user/saveUser",
				type : "post",
				data : data,
				success : function(s) {
					if (s.success) {
						location.reload();
					} else {
						alert(s.msg);
					}
				}
			});
	   }
	   else
	   {
		   var data = {
			   id:userid,
			   orgid:orgid,
			   name:name,
			   status:status
		   }		   
		   $.ajax({
				url : "${request.contextPath}/user/updateUser",
				type : "post",
				data : data,
				success : function(s) {
					if (s.success) {
						location.reload();
					} else {
						alert(s.msg);
					}
				}
			});
	   }
   }
   
   
 </script>